<template>
  <view class="punch-wrapper">
    <view class="punch-back">
      <div class="bgc-theme" style="border-bottom-left-radius: 70%; border-bottom-right-radius: 70%; height: 200px; width: 100vw"></div>
    </view>
    <view class="punch-content">
      <view class="punch-content-tab">
        <view
          v-for="(item, index) in navList"
          :key="index"
          :class="{
            'punch-content-tab-item': true,
            selected: punchTab === index
          }"
          @tap="setPunchTab(index)"
        >{{ item.text }}</view>
      </view>
      <!-- 上下班打卡 -->
      <view v-if="punchTab === 0" class="punch-block-wrapper">
        <!-- 预备页面 -->
        <view v-if="showStatus === -1" class="punch-block">
          <view class="punch-status">
            <img src="/punchcard/img/xiabandaka.png" alt="">
            <view class="tip">请稍等~</view>
          </view>
        </view>
        <!-- 可打卡 -->
        <view v-if="showStatus === 0" class="punch-block">
          <view v-if="rangeStateText === '已在'">
            <view class="punch-title">您{{ rangeStateText }}打卡范围内</view>
            <view class="punch-position">
              <i class="iconfont fs18 tc-theme mr4">&#xe634;</i>
              {{ site.companyName ? site.companyName : "--" }}
            </view>
          </view>
          <view v-if="rangeStateText === '未在'" class="punch-map-wrapper">
            <map
              id="outPunchMap"
              ref="outPunchMap"
              :latitude="latitude"
              :longitude="longitude"
              scale="16"
              :markers="markers"
              class="punch-map"
            />
            <view
              class="punch-title"
              style="margin-top: 160px;font-size: 14px;"
            >您{{ rangeStateText }}打卡范围内{{ checkDetail && checkDetail.exceed ? `，距离边界 ${checkDetail.exceed} 米` : '' }}</view>
          </view>
          <!-- <view v-if="showTimeTip" style="color: red;font-size:14px;">不在打卡时间范围内</view> -->
          <view class="punch-circle" @tap="punch">
            <view class="punch-circle-text">{{ currentTime }}</view>
            <view class="punch-circle-text small">{{ workStatusText }}</view>
          </view>
          <view class="punch-tip">{{ punchTipText }}</view>
        </view>
        <!-- 2.上班已打卡 -->
        <view v-if="showStatus === 1" class="punch-block">
          <view class="punch-status">
            <img src="/punchcard/img/weidaoshijian.png" alt="">
            <view
              class="tip"
            >上班已打卡 <br>
              未到下班打卡时间~</view>
          </view>
          <!-- <view class="punch-tip">{{ punchTipText }}</view> -->
        </view>
        <!-- 3.下班已打卡 -->
        <view v-if="showStatus === 10" class="punch-block">
          <view class="punch-block">
            <view class="punch-status">
              <img src="/punchcard/img/xiabandaka.png" alt="">
              <view class="tip">再忙也要好好休息~</view>
            </view>
            <view class="flex">
              <view
                class="colorFCAF4F"
                style="line-height: 40px;"
                @click="updatePunch"
              >
                打卡更新
              </view>
              <span class="fc1" style="font-weight: 500;font-size: 14px;">{{
                "_" + updateOffWorkTime
              }}</span>
            </view>
          </view>
        </view>
        <!-- 打卡结果 -->
        <!-- 1.打卡成功 -->
        <view v-if="showStatus === 3" class="punch-block">
          <!-- <view class="punch-result-close" @tap="close">
            <icon type="clear" size="26" />
          </view> -->
          <view>
            <img
              v-if="punchAbnormal"
              class="punch-result-image"
              src="/punchcard/img/chidao.png"
              alt=""
            >
            <img
              v-else
              class="punch-result-image"
              src="/punchcard/img/weixiao.png"
              alt=""
            >
            <view class="punch-result-text">{{ punchStatusText }}</view>
            <view class="punch-result-text small">{{ punchTipText }}</view>
          </view>
          <view class="punch-result-detail bottom-border">
            <view class="punch-result-detail-item">
              <view class="punch-result-detail-item-label">时间</view>
              <view
                :class="{
                  'punch-result-detail-item-text': true,
                  abnormal: punchAbnormal
                }"
              >{{ punchTime }}</view>
            </view>
            <view class="punch-result-detail-item">
              <view class="punch-result-detail-item-label">位置</view>
              <view class="punch-result-detail-item-text">{{
                punchLocationshow
              }}</view>
            </view>
          </view>
        </view>
        <!-- 未设置打卡规则 -->
        <view v-if="showStatus === 4" class="punch-block">
          <view class="punch-block">
            <view class="punch-status">
              <img src="/punchcard/img/meiyou.png" alt="">
              <view
                class="tip"
                style="color:#C0C0C0;font-weight: 400;"
              >公司未设置打卡规则 <br>请联系管理员~</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-modal v-model="show" :show-title="false" show-cancel-button confirm-text="确认打卡" :confirmColor="settings.theme" @confirm="onConfirm">
      <view class="check-slot-content">
        <img src="/punchcard/img/xiabandaka.png" alt="">
        <view class="font">你早退了</view>
        <view class="time">{{ currentTime }}</view>
      </view>
    </u-modal>
    <u-modal v-model="showLocation" :show-confirm-button="false">
      <view class="content">
        当前小程序定位未开启，请前往打开
      </view>
      <view class="confirm-button">
        <view @click="showLocation = false">
          取消
        </view>
        <view>
          <button class="weui-btn" type="primary" plain="true" open-type="openSetting" @opensetting='bindopensetting'>确定</button>
        </view>
      </view>
    </u-modal>
  </view>
</template>
<script>

import moment from "moment";
import { getHourtime } from "@/utils/tools.js";
import GPS from "@/utils/gps";
import { checkPunchReq, punchReq, outPunchReq } from "@/services/punchcard";
import { mapState } from "vuex";
import amap from "@/utils/amap-wx";

export default {
  name: "PunchTab",
  components: {},
  data() {
    return {
      amap: null,
      punchTab: 0,
      navList: [
        { text: "上下班打卡" }
        // { text: "外出打卡" }
      ],
      showStatus: -1,
      currentTime: getHourtime(new Date()),
      checkDetail: null,
      updateOffWorkTime: "",
      punchLocationshow: "",
      wifiInfo: {},
      showTimeTip: false,
      workPunch: {
        punchSuccess: false,
        onWorkTime: null,
        onWorkPunchTime: null,
        offWorkTime: null,
        offWorkPunchTime: null,
        punchNumber: null,
        rangeState: -1,
        workStatus: 0,
        punchStatus: 0
      },
      outPunch: {
        instruction: "",
        punchSuccess: false,
        punchTime: null,
        status: false
      },
      allowPunch: true,
      noRule: false,
      location: null,
      markers: [],
      id: 0, // 使用 marker点击事件 需要填写id
      title: "map",
      latitude: 36.088714,
      longitude: 120.38299,
      covers: [
        {
          latitude: 36.088714,
          longitude: 120.38299,
          iconPath: "/punchcard/img/dingwei.png"
        }
      ],
      show: false,
      showLocation: false
    };
  },
  computed: {
    ...mapState(["punchcard", "site", "settings"]),
    punchStatusText: function() {
      // TODO punchStatus为0 时显示空
      return ["", "打卡成功", "上班·迟到", "下班·早退"][
        this.workPunch.punchStatus
      ];
    },
    punchTime: function() {
      switch (this.workPunch.workStatus) {
        case 1:
          return this.workPunch.onWorkPunchTime;
        case 2:
          return this.workPunch.offWorkPunchTime;
        case 3:
          return this.workPunch.offWorkPunchTime;
        default:
          return "--";
      }
    },
    punchAbnormal: function() {
      return (
        this.workPunch.punchStatus === 2 || this.workPunch.punchStatus === 3
      );
    },
    rangeStateText: function() {
      return ["未在", "已在"][this.workPunch.rangeState];
    },
    workStatusText: function() {
      return ["", "上班打卡", "下班打卡", "打卡更新"][
        this.workPunch.workStatus
      ];
    },
    punchTipText: function() {
      switch (this.workPunch.workStatus) {
        case 0:
          return ` `;
        case 1:
          return `请在 ${
            this.workPunch.onWorkTime ? this.workPunch.onWorkTime : "--"
          } 前打卡`;
        case 2:
          return `请在 ${
            this.workPunch.offWorkTime ? this.workPunch.offWorkTime : "--"
          } 后打卡`;
        case 3:
          return `今日已无需打卡`;
        default:
          return "";
      }
    },
    punchRange: function() {
      return ["", "地点异常", "正常外勤", "不允许范围外打卡"][
        this.workPunch.punchRange
      ];
    },
    outPunchStatusText: function() {
      return this.outPunch.status ? "外出打卡·成功" : "外出打卡·失败";
    }
  },
  created() {
    this.amap = new amap.AMapWX({ key: "bcb7099d85eebe967fe5871662bba7bb" });
    this.getlocation();
    this.map = uni.createMapContext("outPunchMap", this);
    if (this.punchcard.instruction) {
      this.outPunch.instruction = this.punchcard.instruction;
    }
    this.$store.commit('punchcard/lat', null);
    this.$store.commit('punchcard/lon', null);
  },
  methods: {
    moment,
    setPunchTab(index) {
      this.punchTab = index;
      if (this.punchTab === 0) {
        this.getlocation();
      }
    },
    getlocation() {
      uni.getLocation({
        type: "wgs84",
        geocode: true,
        success: res => {
          const gcj = GPS.gcj_encrypt(res.latitude, res.longitude);
          this.markers = [this.generateMarker(gcj.lat, gcj.lon)];
          this.latitude = gcj.lat;
          this.longitude = gcj.lon;
          this.$store.commit('punchcard/lat', this.latitude);
          this.$store.commit('punchcard/lon', this.longitude);
          this.getLocationInfo();
        },
        fail: err => {
          console.log("debug log --> ", err);
          this.getMsg(err.errMsg);
        }
      });
    },
    getMsg(msg) {
      switch(msg){
        case 'getLocation:fail 频繁调用会增加电量损耗，可考虑使用 onLocationChangeAPI 监听地理位置变化':
          const latitude = this.$store.state.punchcard.lat;
          const longitude = this.$store.state.punchcard.lon;
          const gcj = GPS.gcj_encrypt(latitude, longitude);
          this.markers = [this.generateMarker(gcj.lat, gcj.lon)];
          this.latitude = gcj.lat;
          this.longitude = gcj.lon;
          this.getLocationInfo();
          break;
        case 'getLocation:fail auth deny':
          console.log("小程序重新调起授权")
          this.showLocation = true;
          break;
        case 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF':
          uni.showToast({
            title: "请检查手机定位是否开启，或切换网络环境重启微信或系统然后尝试",
            icon: "none",
            duration: 2000
          });
          break;
        case 'getLocation:fail:system permission denied':
          uni.showToast({
            title: "请检查手机应用定位权限是否开启",
            icon: "none",
            duration: 2000
          });
          break;
        case 'getLocation:fail system permission denied':
          uni.showToast({
            title: "请检查手机应用定位权限是否开启",
            icon: "none",
            duration: 2000
          });
          break;
        default:
          uni.showToast({
            title: msg,
            icon: "none",
            duration: 2000
          });
      };
    },
    bindopensetting(e) {
      if(e.detail.authSetting['scope.userLocation']){
        this.showLocation = false;
        this.getlocation();
      }
    },
    checkPunch() {
      checkPunchReq({
        latitude: this.latitude,
        longitude: this.longitude,
        macAddr: this.wifiInfo.BSSID,
        wifiName: this.wifiInfo.SSID,
        punchLocation: this.location
      })
        .then(res => {
          console.log(res);
          this.showStatus = 0;
          this.checkDetail = res;
          if (res.isSetPlan === false) {
            this.showStatus = 4;
          }
          if (res.isWhitelist === true) {
            uni.showModal({
              title: "温馨提示",
              content: "当前用户不在打卡规则内，无需打卡",
              showCancel: false,
              confirmText: "知道了"
            });
          }
          if (res.isTodayAttend === false) {
            uni.showModal({
              title: "温馨提示",
              content: "今日无需打卡",
              showCancel: false,
              confirmText: "知道了"
            });
          }
          if (res.isInPunchTime === false) {
            this.showTimeTip = true;
            uni.showModal({
              title: "温馨提示",
              content: "不在打卡时间范围内",
              showCancel: false,
              confirmText: "知道了"
            });
          }
          if (res.completedWork === true && res.workStatus === 1) {
            this.showStatus = 1;
          }
          if (res.completedWork === true && res.workStatus === 2) {
            this.showStatus = 0;
          }
          this.workPunch.onWorkTime = res.onWorkTime
            ? res.onWorkTime.substring(res.onWorkTime.length - 5)
            : "--";
          this.workPunch.offWorkTime = res.offWorkTime
            ? res.offWorkTime.substring(res.offWorkTime.length - 5)
            : "--";
          this.workPunch.punchNumber = res.punchNumber;
          this.workPunch.punchStatus = res.punchStatus;
          this.workPunch.rangeState = res.rangeState;
          this.workPunch.workStatus = res.workStatus;
          this.workPunch.punchLocation = res.punchLocation;
          // this.punchLocationshow = res.rangeState === 1 ? "公司范围内" : res.punchLocation
          this.updateOffWorkTime = res.offWorkPunchTimeLast
            ? res.offWorkPunchTimeLast.substring(
              res.offWorkPunchTimeLast.length - 8,
              res.offWorkPunchTimeLast.length - 3
            )
            : "--";
        })
        .catch(err => {
          console.log("debug log --> ", err);
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000
          });
        });
    },
    punch() {
      if (this.checkDetail.isWhitelist === true) {
        uni.showModal({
          title: "温馨提示",
          content: "当前用户不在打卡规则内，无需打卡",
          showCancel: false,
          confirmText: "知道了"
        });
        return;
      }
      if (this.checkDetail.isTodayAttend === false) {
        uni.showModal({
          title: "温馨提示",
          content: "今日无需打卡",
          showCancel: false,
          confirmText: "知道了"
        });
        return;
      }
      if (this.checkDetail.isInPunchTime === false) {
        uni.showModal({
          title: "温馨提示",
          content: "当前不在打卡时间范围内",
          showCancel: false,
          confirmText: "知道了"
        });
        return;
      }
      var that = this;
      if (this.checkDetail.rangeState === 0) {
        if (this.checkDetail.punchRange === 3) {
          uni.showModal({
            title: "温馨提示",
            content: "当前规则不允许范围外打卡",
            showCancel: false,
            confirmText: "知道了"
          });
        } else {
           uni.showModal({
              title: "温馨提示",
              content: "当前不在打卡范围内\n是否确认打卡？",
              success: function(res) {
                if (res.confirm) {
                  that.punchClick();
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              }
            });
          // 范围外能不能打卡
          // wifi不匹配

          // if(this.checkDetail.isWifiConfig === true) {
          //   if (this.checkDetail.isWifiMatch === false) {
          //     uni.showModal({
          //       title: "温馨提示",
          //       content: "wifi不匹配",
          //       showCancel: false,
          //       confirmText: "知道了"
          //     });
          //   } else {
          //     uni.showModal({
          //       title: "温馨提示",
          //       content: "当前不在打卡范围内\n是否确认打卡？",
          //       success: function(res) {
          //         if (res.confirm) {
          //           that.punchClick();
          //         } else if (res.cancel) {
          //           console.log("用户点击取消");
          //         }
          //       }
          //     });
          //   }
          // }else{

          // }

        }
      } else if (this.checkDetail.rangeState === 1) {

        // const offWorkTime = `${moment().format("YYYY-MM-DD")} 15:00`;

        if (
          this.checkDetail.isWhitelist === false &&
          this.checkDetail.isTodayAttend === true
        ) {
          if (this.checkDetail.isInPunchTime === true) {
            const currentTime = `${moment().format("YYYY-MM-DD")} ${this.currentTime}`;
            const offWorkTime = `${moment().format("YYYY-MM-DD")} ${this.workPunch.offWorkTime}`;
            if(this.workStatusText === '下班打卡' && moment(currentTime).unix() < moment(offWorkTime).unix()) {
              this.show = true;
            } else {
              this.punchClick();
            }
            // this.punchClick();
          }
        }
      } else {
        // fanweinei
        that.intro = JSON.stringify(that.checkDetail);
        uni.showModal({
          title: "温馨提示",
          content: "请求失败，请联系管理员",
          showCancel: false,
          confirmText: "知道了"
        });
      }
      // }else{
      // uni.showModal({
      //   title: '温馨提示',
      //   content: '服务错误，请联系管理员',
      //   showCancel: false,
      //   confirmText: '知道了'
      // })
      // }
    },
    onConfirm() {
      this.punchClick();
    },
    punchClick() {
      punchReq({
        latitude: this.latitude,
        longitude: this.longitude,
        macAddr: this.wifiInfo.BSSID,
        wifiName: this.wifiInfo.SSID,
        punchLocation: this.location,
        punchNumber: this.workPunch.punchNumber,
        rangeState: this.workPunch.rangeState
      }).then(res => {
        switch (res.workStatus) {
          case 1:
            this.workPunch.onWorkPunchTime = res.onWorkPunchTime.substring(
              0,
              5
            );
            break;
          case 2:
            this.workPunch.offWorkPunchTime = res.offWorkPunchTime;
            break;
          default:
            break;
        }
        this.workPunch.punchStatus = res.punchStatus;
        this.updateOffWorkTime = res.offWorkPunchTimeLast
          ? res.offWorkPunchTimeLast.substring(
            res.offWorkPunchTimeLast.length - 8,
            res.offWorkPunchTimeLast.length - 3
          )
          : "--";
        this.workPunch.punchSuccess = true;
        this.punchLocationshow =
          this.workPunch.rangeState === 1 ? "公司范围内" : res.punchLocation;
        this.showStatus = 3;
      });
    },
    updatePunch() {
      punchReq({
        latitude: this.latitude,
        longitude: this.longitude,
        macAddr: this.wifiInfo.BSSID,
        wifiName: this.wifiInfo.SSID,
        punchNumber: this.workPunch.punchNumber
      }).then(res => {
        switch (res.workStatus) {
          case 1:
            this.workPunch.onWorkPunchTime = res.onWorkPunchTime.substring(
              0,
              5
            );
            break;
          case 2:
            this.workPunch.offWorkPunchTime = res.offWorkPunchTime.substring(
              0,
              5
            );
            break;
          default:
            break;
        }
        this.workPunch.punchStatus = res.punchStatus;
        this.updateOffWorkTime = res.offWorkPunchTimeLast
          ? res.offWorkPunchTimeLast.substring(
            res.offWorkPunchTimeLast.length - 8,
            res.offWorkPunchTimeLast.length - 3
          )
          : "--";
        this.workPunch.punchSuccess = true;
        this.showStatus = 3;
      });
    },
    punchOutside() {
      outPunchReq({
        latitude: this.latitude,
        longitude: this.longitude,
        location: this.location,
        outExplain: this.outPunch.instruction
      })
        .then(res => {
          if (res.status) {
            this.outPunch.punchSuccess = true;
            this.outPunch.punchTime = res.punchTime.substring(0, 5);
            this.outPunch.status = res.status;
          } else {
            uni.showToast({
              title: "外出打卡失败",
              icon: "none",
              duration: 2000
            });
          }
        })
        .catch(err => {
          console.log("debug log --> ", err);
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000
          });
        });
    },
    goInstruction() {
      uni.navigateTo({
        url: "/punchcard/instruction"
      });
    },
    generateMarker(lat, lon) {
      return {
        id: 0,
        latitude: lat,
        longitude: lon,
        iconPath: "/punchcard/img/dingwei.png",
        width: 30,
        height: 30,
        title: "当前不在打卡范围内"
      };
    },
    close() {
      uni.navigateBack();
    },
    getLocationInfo() {
      var that = this;
      this.amap.getPoiAround({
        location: `${this.longitude},${this.latitude}`,
        querytypes: "190000",
        success: function(res) {
          that.location = res && res.markers && res.markers.length > 0 ? res.markers[0]["name"] : null
          wx.startWifi({
            success: function() {
              wx.getConnectedWifi({
                success: function(cfRes) {
                  that.wifiInfo = cfRes.wifi;
                  that.checkPunch();
                },
                fail(err) {
                  console.log("debug log -err1-> ", err);
                  that.checkPunch();
                }
              });
            },
            fail(err) {
              console.log("debug log -err2-> ", err);
              that.checkPunch();
            }
          });
        },
        fail: function(err) {
          console.log("debug log --> ", err);
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000
          });
          that.checkPunch();
        }
      });
    }
    // TODO 打卡拍照
  }
};
</script>
